<?php

function sp_get_url_route(){
	$apps=sp_scan_dir(SPAPP."*",GLOB_ONLYDIR);
	$host=(is_ssl() ? 'https' : 'http')."://".$_SERVER['HTTP_HOST'];
	$routes=array();
	foreach ($apps as $a){
	
		if(is_dir(SPAPP.$a)){
			if(!(strpos($a, ".") === 0)){
				$navfile=SPAPP.$a."/nav.php";
				$app=$a;
				if(file_exists($navfile)){
					$navgeturls=include $navfile;
					foreach ($navgeturls as $url){
						//echo U("$app/$url");
						$nav= file_get_contents($host.U("$app/$url"));
						$nav=json_decode($nav,true);
						if(!empty($nav) && isset($nav['urlrule'])){
							if(!is_array($nav['urlrule']['param'])){
								$params=$nav['urlrule']['param'];
								$params=explode(",", $params);
							}
							sort($params);
							$param="";
							foreach($params as $p){
								$param.=":$p/";
							}
							
							$routes[strtolower($nav['urlrule']['action'])."/".$param]=$nav['urlrule']['action'];
						}
					}
				}
					
			}
		}
	}
	
	return $routes;
}

/**
 * @param $id
 * @return mixed
 * 根据帮助类别ID获取类别名称
 */
function getTypeName($id)
{
	$help_type = M("help_type");
	$ret = $help_type->where(array('help_type_id'=>$id))->field('help_name')->find();
	return $ret['help_name'];
}
/**
 * 根据用户ID获取用户昵称
 * @param $uid 用户ID
 * @return mixed
 *
 */
function getUserName($uid)
{
	$app_users = M("app_users");
	$ret = $app_users->where(array('user_id'=>$uid))->field('user_name')->find();
	return $ret['user_name'];
}
/**
 * 根据用户ID获取用户电话
 * @param $uid 用户ID
 * @return mixed
 *
 */
function getUserMobile($uid)
{
	$app_users = M("app_users");
	$ret = $app_users->where(array('user_id'=>$uid))->field('mobile')->find();
	return $ret['mobile'];
}
/**
 * 根据用户ID获取跑客姓名
 * @param $uid 用户ID
 * @return mixed
 *
 */
function getDispatchName($uid)
{
	$app_users = M("dispatch");
	$ret = $app_users->where(array('dispatch_id'=>$uid))->field('dispatch_name')->find();
	return $ret['dispatch_name'];
}
/**
 * 根据跑客id获取电话
 * @param $uid 用户ID
 * @return mixed
 *
 */
function getDispatchMobile($uid)
{
	$app_users = M("dispatch");
	$ret = $app_users->where(array('dispatch_id'=>$uid))->field('mobile')->find();
	return $ret['mobile'];
}
/**
 * @param $id
 * @return mixed
 * 根据城市ID获取城市名称
 */
function getCityName($city_id)
{
	$location = M("location");
	$ret = $location->where(array('id'=>$city_id))->field('city')->find();
	return $ret['city'];
}
/**
 * 根据公告主键id，获得公告标题
 * @return array 最新的10条消息
 */
function get_noticeTitle($notice_id){

	if(!$notice_id || $notice_id == 0)
		return "";
	$notice_db = M('message');
	$list = $notice_db
		->field('title')
		->order("send_time DESC")
		->limit( '0,10')
		->where('message_id='.$notice_id)
		->find();
	$title = $list['title'];
	return $title;
}
/**
 * 根据订单ID获取订单号
 * @param $uid 用户ID
 * @return mixed
 *
 */
function getOrderNo($oid)
{
	$app_users = M("order");
	$ret = $app_users->where(array('order_id'=>$oid))->field('order_number')->find();
	return $ret['order_number'];
}
/**
 * @param $id
 * @return mixed
 * 根据城市ID获取城市名称
 */
function getCityList($province_id)
{
	$location = M("location");
	$ret = $location->where(array('province_id'=>$province_id))->field('id as city_id,city as city_name')->order('sort')->select();
	return $ret;
}
/**
 * @param $id
 * @return mixed
 * 根据城市ID获取省名称
 */
function getProvinceNameForCity($city_id)
{
	$location = M("location");
	$ret = $location->where(array('id'=>$city_id))->field('state')->find();
	return $ret['state'];
}
/**
 * @param $id
 * @return mixed
 * 根据省ID获取省名称
 */
function getProvinceName($province_id)
{
	$location = M("location");
	$ret = $location->where(array('province_id'=>$province_id))->field('state')->find();
	return $ret['state'];
}
/**
 * @param $id
 * @return mixed
 * 根据城市ID获取省id
 */
function getProvinceId($company_id)
{
	$location = M("location");
	$ret = $location->where(array('id'=>$company_id))->field('province_id')->find();
	return $ret['province_id'];
}
/**
 * 根据团队id，获取团队名称
 * @param $company_id
 * @return int
 */
function getCompanyName($company_id){
	if(!$company_id)
		return "";
	$com_db = M('company');
	$com_obj = $com_db->where('company_id='.$company_id)->find();

	if($com_obj)
		return $com_obj['company_name'];
	else
		return "";
}
/**
 * 根据物品类别id，获取所属类别集合
 * @param $type  1：取送类别，2：代买类别，3：排队类别
 * @return int
 */
function getResType($type){
	$res_type_db= M('res_type');
	$res_type_obj = $res_type_db->where('type='.$type)->order('type,sort')->select();

	if($res_type_obj)
		return $res_type_obj;
	else
		return 0;
}
/**
 * 根据物品类别主键id，获取类别名称
 * @param $res_type_id  主键id
 * @return int
 */
function getResTypeName($res_type_id){
	$res_type_db= M('res_type');
	$res_type_obj = $res_type_db->where('res_type_id='.$res_type_id)->find();

	if($res_type_obj)
		return $res_type_obj['res_type'];
	else
		return 0;
}

/**
 * 根据团队id，获取团队所在的城市id
 *
 */
function getCompanyCity($company_id)
{
	if(!$company_id)
		return 0;
	$company_db = M('company');

	$company_obj = $company_db->where('company_id='.$company_id)->find();

	if($company_obj)
		return $company_obj['city_id'];
	else
		return 0;

}
function getConveyanceName($id){
	if(!$id)
		return 0;
	$company_db = M('conveyance');

	$company_obj = $company_db->where('conveyance_id='.$id)->find();

	if($company_obj)
		return $company_obj['conv_name'];
	else
		return 0;
}
function getUserLevel($level_id){
	$level_db = M('user_level');

	$level_obj = $level_db->where(array('user_level_id'=>$level_id))->find();

	if($level_obj)
		return $level_obj['level_name'];
	else
		return "";
}
function getDispatchLevel($level_id){
	$level_db = M('dispatch_level');

	$level_obj = $level_db->where(array('dispatch_level_id'=>$level_id))->find();

	if($level_obj)
		return $level_obj['level_name'];
	else
		return "";
}
/**
 * 分配给跑客订单
 * @param $voucher_no
 * @param $dispatch_id
 * @param $dispatch_get_money
 * @return string
 */
function option_pnRobOrder($voucher_no,$dispatch_id,$dispatch_get_money)
{
	//跑客端接口权限校验
	$order = M('order');
    $order_resmsm = M('order_resmsm');
	$order_pay = M('order_pay');
	//反查得到order_id
	$order_id = $order_pay->where(array('voucher_no' => $voucher_no))->field('order_id')->find();
//        dump($order_id);
	//查出来指定的订单ID，并且是待分配的
	$rets = $order->where(array('order_id' => $order_id['order_id']))->find();

	if (1 == $rets['status']) {
		//抢单人员的策略在此执行
		//1.抢单人员必须提交了相关资料（db_dispatch中is_audit为2）
		$dispatch = M('dispatch');
		//查询派单员是否审核通过
		$retdis = $dispatch->where(array('dispatch_id' => $dispatch_id,'is_sign'=>2,'account_status'=>1))->field('dispatch_id')->find();

		//判断派单员的审核状态
		//是否审核通过(0 未提交审核 1已提交审核，2已经审核通过 3审核未通过)

//		$count = $order->where('dispatch_id='.$dispatch_id.' and status>1 and status<7')->count();

//		if( $count==2){
//			$order_count = $order->where('dispatch_id='.$dispatch_id.' and status>1 and status<7')->field('is_reservation')->find();
//			if($order_count['is_reservation'] == 0) {
//				if ($rets['is_reservation'] == 0) {
//					return array('retCode'=>1, 'retDesc'=>"您已经有两单即时任务了，您现在只能接收预约任务");
//				}
//			}else{
//				if ($rets['is_reservation'] == 1) {
//					return array('retCode'=>1, 'retDesc'=>"您已经有预约任务了，您现在只能接收即时任务");
//				}
//			}
//		}else if($count>3){
//			return array('retCode'=>1, 'retDesc'=> "您已经有足够的任务啦");
//		}


		$order->startTrans();

		//每天首单扣除保险费
//                    $insu_ret = save_dispatch_insurance(I('uid'), $order_id['order_id'], 2);
		//$insu_ret = dispatch_insurance_options($dispatch_id,$order_id['order_id'],-2,6,'扣除保险费','每天首次接单扣除保险费2.00元','这是一个指派单，并且是您今天的首单（'.$rets['order_number'].'），扣除保险费2.00元');
//                    dump($insu_ret);
		//if(0==$insu_ret){
		//	$order->rollback();
		//	RET_NO_V(1, "这是一个分配订单，并且是您今天首单，保险费扣除失败");
		//}
		//此派单员已经签约通过，进行订单更改和抢单操作
		$ret = $order->where(array('order_id' => $order_id['order_id']))->save(array(
			//更改单子的抢单状态
			'status' => 2,
			//派单员ID更新
			'dispatch_id' => $dispatch_id,
			//更改单子抢单最后时间
			'dispatch_end_time' => date('Y-m-d H:i:s'),
			'dispatch_get_money'=>$dispatch_get_money,//跑腿费
			'is_appoint'=>2  //手动分配  状态
		));

        //更改中间表已分配
        $order_status = $order_resmsm->where(array('order_id'=>$order_id['order_id']))->save(array('status'=>2,'dispatch_id'=>$dispatch_id));
		//判断抢单是否成功
		if ($ret && $order_status) {
			$msg_ret = create_user_message($rets['user_id'],'订单已被接收','订单（'.$rets['order_number'].'）已被接收','您的订单（'.$rets['order_number'].'）已被跑客接收，即刻为您完成');

			if(!$msg_ret){
				$order->rollback();
				return array('retCode'=>1, 'retDesc'=>"插入用户消息失败");
			}else{
				$order->commit();
				return array('retCode'=>0, 'retDesc'=>"分配订单成功");
			}
		} else {
			//抢单失败
			$order->rollback();
			return array('retCode'=>1, 'retDesc'=>"分配订单失败");
		}
	}else if(9 == $rets['status']){
		return array('retCode'=>2, 'retDesc'=>"订单已取消！");
	}else{
		return array('retCode'=>2, 'retDesc'=>"已经有人抢单！");
	}
}


/**
 * 根据用户ID获取 平台的分成金额
 * @param $uid 用户ID
 * @return mixed
 *
 */
function getPlatformSeparateIncome($order_id)
{
	$ret = null;

	$app_users = M("systurnover");
	$ret = $app_users->where(array('orderid=' . $order_id . ' and income_type=2'))->field('separate_income')->find();

	return $ret['separate_income'] ? $ret['separate_income'] : 0;
}
/**
 * 根据用户ID获取 用户或跑客的分成金额
 * @param $uid 用户ID
 * @return mixed
 *
 */
function getUserSeparateIncome($order_id, $uid, $utype)
{
	$ret = null;

	if ($utype == 1) {
		$app_users = M("user_purse");
		$ret = $app_users->where(array('user_id' => $uid , 'order_id'=> $order_id , 'purse_type'=>6))->field('purse_amount as user_income')->find();
	}
	if ($utype == 2) {
		$app_users = M("dispatch_balance");
		$ret = $app_users->where(array('dispatch_id' => $uid , 'order_id'=> $order_id, 'balance_type'=>5))->field('balance_amount as user_income')->find();
	}
	return $ret['user_income'];
}
/**
 * 根据订单ID获取 用户优惠券面值
 * @param $uid 用户ID
 * @return mixed
 *
 */
function getCouponValue($order_id,$user_id)
{
	$order_db = M('order');
	$order_obj = $order_db->where(array('order_id'=>$order_id,'user_id'=>$user_id))->find();
	$coupon_amount='0.00';
	if($order_obj){
		$coupon_obj = M('user_coupon')->where(array('user_coupon_id'=>$order_obj['coupon_id']))->find();
		if($coupon_obj){
			if($coupon_obj['coupon_type']==1){
				$coupon_amount=$coupon_obj['coupon_value'];
			}
			elseif($coupon_obj['coupon_type']==2){
				$coupon_amount=$order_obj['order_amount']*(1-$coupon_obj['coupon_value']/100);
			}
		}

	}
	return format_money($coupon_amount,2);
}
/**
 * 根据订单ID获取 用户优惠金额
 * @param $uid 用户ID
 * @return mixed
 *
 */
function getOrderCoupon($order_id,$user_id)
{
	if(!$order_id || !$user_id)
		return '0.00';
	$order_db = M('order');
	$order_obj = $order_db->where(array('order_id'=>$order_id,'user_id'=>$user_id))->find();
	$coupon_amount='0.00';
	if($order_obj){
		$coupon_obj = M('user_coupon')->where(array('user_coupon_id'=>$order_obj['coupon_id']))->find();
		if($coupon_obj){
			if($coupon_obj['coupon_type']==1){
				if($coupon_obj['coupon_value']>$order_obj['order_amount'])
					$coupon_amount=$order_obj['order_amount'];
				else
					$coupon_amount=$coupon_obj['coupon_value'];
			}
			elseif($coupon_obj['coupon_type']==2){
				$coupon_amount=$order_obj['order_amount']*(1-$coupon_obj['coupon_value']/100);
			}
		}

	}
	return format_money($coupon_amount,2);
}

/**
 * 根据订单ID、跑客id获取 跑客的推荐人的奖励
 * @param $uid 用户ID
 * @return mixed
 *
 */
function getRecommendPn($order_id,$dispatch_id)
{
	if(!$order_id || !$dispatch_id)
		return '0.00';
	$recommend_db = M('recommend');
	$recommend_obj = $recommend_db->where(array('recommended_person_id'=>$dispatch_id,'recommended_person_type'=>2))->find();
	$recommend_amount='0.00';
	if($recommend_obj){
		if($recommend_obj['recom_person_type']==1){//推荐人是用户
			$user_purse_db=M('user_purse');
			$user_purse_obj = $user_purse_db->where(array('order_id'=>$order_id,'user_id'=>$recommend_obj['recom_person_id'],'purse_type'=>6))->find();

			$recommend_amount=$user_purse_obj['purse_amount'];
		}elseif ($recommend_obj['recom_person_type']==2){//推荐人是跑客
			$dispatch_balance_db=M('dispatch_balance');
			$dispatch_balance_obj = $dispatch_balance_db->where(array('order_id'=>$order_id,'dispatch_id'=>$recommend_obj['recom_person_id'],'balance_type'=>5))->find();

			$recommend_amount=$dispatch_balance_obj['balance_amount'];
		}
	}

	return format_money($recommend_amount,2);
}


/**
 * 封装用户资金记录的方法
 * @user_id int 用户ID
 * @purse_type int 类型:1、充值，2、消费，3、退款，4、代收货款结算，5、提款
 * @purse_amount int 变动金额 10
 * @change_remark string 变动说明(活动说明之类)
 * @recharge_record_id int 充值记录id
 * @order_id int 订单ID
 * @user_set_id int 代收款id
 * @cash_record_id int 提款记录id
 */
function userPurseLog($user_id, $purse_type, $purse_amount, $change_remark, $recharge_record_id, $order_id, $user_set_id = NULL, $cash_record_id = NULL)
{
    $user_purse = M('user_purse');
    $data = array(
        'user_id' => $user_id,
        'purse_type' => $purse_type,
        'purse_amount' => $purse_amount,
        'change_time'=>date('Y-m-d H:i:s',time()),
        'change_remark' => $change_remark,
        'recharge_record_id' => $recharge_record_id,
        'order_id' => $order_id,
        'user_set_id' => $user_set_id,
        'cash_record_id' => $cash_record_id,
		'sum_amount'=>get_user_balance($user_id) + $purse_amount
    );
    return $user_purse->add($data);
}

/**
 * 封装跑客资金记录的方法
 */
function dispatchPurseLog($dispatch_id, $balance_type, $balance_amount, $change_memo, $remark, $order_id, $user_set_id = NULL, $coin_id = NULL)
{
    $dispatch_balance = M('dispatch_balance');
    $data = array(
        'dispatch_id' => $dispatch_id,
        'balance_type' => $balance_type,
        'balance_amount' => $balance_amount,
        'time'=>date('Y-m-d H:i:s',time()),
        'change_memo' => $change_memo,
        'remark'=>$remark,
        'order_id' => $order_id,
        'cash_record_id' => $user_set_id,
        'coin_id' => $coin_id,
		'sum_amount'=>get_dispatch_balance($dispatch_id)+$balance_amount
    );
    return $dispatch_balance->add($data);
}

/**
 * 预约转即时
 * @param $order_id
 */
function reser_to_immedi($order_id){
	$order_db = M('order');
	$order_obj = $order_db ->where('order_id='.$order_id.' and status > 1 and status < 7')->find();

	if($order_obj){
		$up_ret = $order_db->where(array('order_id'=>$order_id))->save(array('is_reservation'=>0,'reservation_time'=>null));
		if($up_ret){
			return true;
		}else
			return false;
	}else{
		return false;
	}
}
function order_return_user($order_id,$user_id){
	$order_db = M('order');
	$order_obj = $order_db ->where('order_id='.$order_id.'  and status > 1 and status < 7 and user_id='.$user_id)->find();
	if($order_obj){//存在可以取消的订单

	}
}
/**
 * 跑客接单数量
 */
function pnrob_count($dispatch_id,$order_time){
	$order_db = M('order');
	//".date('Y-m-d',time()))->count();
	$order_count = $order_db ->where("dispatch_id=".$dispatch_id." and status>1 and status <= 7 and DATE_FORMAT(order_time,'%Y-%m-%d') =  DATE_FORMAT('".$order_time."','%Y-%m-%d')")->count();

	return $order_count;
}

/**
 * 个性化时间
 */
function tranTime($time) {
	if(!$time)
		return "";
    $time = strtotime($time);
    $rtime = date("m-d H:i",$time);
    $htime = date("H:i",$time);

    $time = time() - $time;

    if ($time < 60) {
        $str = '方才';
    }
    elseif ($time < 60 * 60) {
        $min = floor($time/60);
        $str = $min.'分钟前';
    }
    elseif ($time < 60 * 60 * 24) {
        $h = floor($time/(60*60));
        $str = $h.'小时前 '.$htime;
    }
    elseif ($time < 60 * 60 * 24 * 3) {
        $d = floor($time/(60*60*24));
        if($d==1)
            $str = '昨天 '.$rtime;
        else
            $str = '前天 '.$rtime;
    }
    else {
        $str = $rtime;
    }
    return $str;
}

/**
 * 根据分公司id，获取分公司名称
 * @param $company_branch_id 分公司id
 * @return string 分公司名称
 */
function get_combranch_name($company_branch_id){
	$com_branch_db = M('company_branch');
	$com_branch_obj = $com_branch_db->where(array('id'=>$company_branch_id))->find();
	if($com_branch_obj)
		return $com_branch_obj['b_name'];
	else
		return "";
}

/**
 * 根据团队id，分公司id，得出总签约人数
 * @param $comany_id 团队id
 * @param $company_branch 分公司id
 * @return string
 */
function get_sign_count($comany_id,$company_branch){

	$where = 'd.is_sign = 2 and d.company_id = '.$comany_id;
	if($company_branch != -1)
		$where = $where.' and case when d.company_branch is null then 0 ELSE d.company_branch end ='.$company_branch;

	$com_branch_obj = M('dispatch d ')->field('count(*) as sign_count')->where($where)->find();
	if($com_branch_obj)
		return $com_branch_obj['sign_count'];
	else
		return "";
}

/**
 *
 * 根据团队id，分公司id，得出总听单人数
 * @param $comany_id  团队id
 * @param $company_branch 分公司id
 * @return string
 */
function get_work_count($comany_id,$company_branch){

	$where = 'd.is_sign = 2 and work_status=1 and d.company_id = '.$comany_id;
	if($company_branch != -1)
		$where = $where.' and case when d.company_branch is null then 0 ELSE d.company_branch end ='.$company_branch;

	$com_branch_obj = M('dispatch d ')->field('count(*) as work_count')->where($where)->find();
	if($com_branch_obj)
		return $com_branch_obj['work_count'];
	else
		return "";
}

/**
 * 根据跑客id，开始时间，结束时间，查询时间段内，这个跑客完成的订单数
 * @param $dispatch_id  跑客id
 * @param $start_time  订单完成的开始时间
 * @param $end_time  订单完成的结束时间
 * @return string   订单数量
 */
function get_dispatch_finish_order($dispatch_id,$start_time,$end_time){

	$time_where = 'o.status=7 and dispatch_id='.$dispatch_id;
	if(!empty($start_time))
		$time_where = $time_where." and finish_time >= '".$start_time."  00:00:00'";
	if(!empty($end_time))
		$time_where = $time_where." and finish_time <= '".$end_time." 23:59:59' ";

	$order_obj = M('order o ')->field('count(o.order_id) as finish_count')->where($time_where)->find();
	if($order_obj)
		return $order_obj['finish_count'];
	else
		return "";
}
/**
 * 根据用户id，开始时间，结束时间，查询时间段内，这个用户下单并且完成的订单数
 * @param $dispatch_id  跑客id
 * @param $start_time  订单完成的开始时间
 * @param $end_time  订单完成的结束时间
 * @return string   订单数量
 */
function get_user_finish_order($user_id,$start_time=null,$end_time=null){

	$time_where = 'o.status=7 and user_id='.$user_id;
	if(!empty($start_time))
		$time_where = $time_where." and finish_time >= '".$start_time."  00:00:00'";
	if(!empty($end_time))
		$time_where = $time_where." and finish_time <= '".$end_time." 23:59:59' ";

	$order_obj = M('order o ')->field('count(o.order_id) as finish_count')->where($time_where)->find();
	if($order_obj)
		return $order_obj['finish_count'];
	else
		return "";
}
/**
 * 根据推荐人id，被推荐人的类型，得出团队中的每个人推荐的人数
 * @param $uid  跑客id 为空，不特指某个团队
 * @param $recom_person_type 推荐人类别1：用户，2跑客  ，不能为空
 * @param $recommended_person_type 被推荐人类别1：用户，2跑客 为空则是推荐的所有人
 * @return string
 */
function get_recommended_person_count($uid,$recom_person_type,$recommended_person_type){

	if(!$uid && !$recom_person_type)
		return "0" ;

	if($recommended_person_type)
		$where = " and recommended_person_type=".$recommended_person_type;

	$sql = "select d.dispatch_id,count(r.recommended_person_id) as recom_count from db_recommend r ".
		" LEFT JOIN db_dispatch d on r.recom_person_id = d.dispatch_id ".
		" where r.recom_person_type = ".$recom_person_type ." and recom_person_id = ".$uid.$where.
		" GROUP BY d.dispatch_id ,r.recommended_person_type";

	$ret_obj = M()->query($sql);

	if($ret_obj)
		return $ret_obj[0]['recom_count'];
	else
		return "0";
}
/**
 * 根据推荐人id，被推荐人的类型，得出团队中的每个人推荐的人的下单量
 * @param $uid  跑客id 为空，不特指某个团队
 * @param $recom_person_type 推荐人类别1：用户，2跑客  ，不能为空
 * @param $recommended_person_type 被推荐人类别1：用户，2跑客 为空则是推荐的所有人
 * @return string
 */
function get_recommended_person_order_count($uid,$recom_person_type,$recommended_person_type){

	if(!$uid && !$recom_person_type)
		return "0" ;

	if($recommended_person_type)
		$where = " and recommended_person_type=1";

	$sql = "select GROUP_CONCAT(r.recommended_person_id) as recommended_person_id from db_recommend r ".
		" where recommended_person_type=1 and r.recom_person_type = ".$recom_person_type ." and recom_person_id = ".$uid.
		" GROUP BY  recom_person_id, r.recommended_person_type";

	$recommended_person_obj = M()->query($sql);
	$recommended_person_ids = $recommended_person_obj[0]['recommended_person_id'];
	if($recommended_person_ids)
		$order_sql = "select  count(o.order_id) as user_order_count from db_order o where o.user_id in(".$recommended_person_ids.") and o.`status` =7";
	else
		return "0";
	$ret_objs = M()->query($order_sql);

	if($ret_objs)
		return $ret_objs[0]['user_order_count'];
	else
		return "0";
}
/**
 * 根据被推荐人id，被推荐人的类型，获取完成单量
 * @param $uid  跑客id 为空
 * @param $recom_person_type 推荐人类别1：用户，2跑客  ，不能为空
 * @param $recommended_person_type 被推荐人类别1：用户，2跑客 为空则是推荐的所有人
 * @return string
 */
function recommended_person_order_count($recommended_person_id,$recommended_person_type){

	if(!$recommended_person_id && !$recommended_person_type)
		return "0" ;
	$order_db = M('order');
	if($recommended_person_type == 1 ){
		$order_count = $order_db->where(array('user_id'=>$recommended_person_id,'status'=>7))->count();
	}elseif ($recommended_person_type == 2 ){
		$order_count = $order_db->where(array('dispatch_id'=>$recommended_person_id,'status'=>7))->count();
	}

	return $order_count;
}
/**
 * 推荐关系树
 */
static $result = array();
function recom_tree($parent_id, $parent_type)
{

	if( !$parent_id || !$parent_type)
		return "";
	$app_distribution = M("recommend");
	$app_user_db = M("app_users");
	$dispatch_db = M('dispatch');
	$order_db = M('order');

	if($parent_type == 1 ){
		$parent_info = $app_user_db->where(array('user_id' => $parent_id))->field('mobile')->find();
		$order_count = $order_db->where(array('status' => 7 ,'user_id' => $parent_id))->count();
		if($order_count>0)
			$result['name'] = $parent_info['mobile'].'下单量（'.$order_count.'单）';
		else
			$result['name'] = $parent_info['mobile'].'（用户）';
	}
	elseif($parent_type == 2 ){
		$parent_info = $dispatch_db->where(array('dispatch_id' => $parent_id))->field('mobile,dispatch_name')->find();
		$order_count = $order_db->where(array('status' => 7 ,'dispatch_id' => $parent_id))->count();
		$name = $parent_info['mobile'];
		if($parent_info['dispatch_name'])
			$name = $parent_info['dispatch_name'].'('.$parent_info['mobile'].')';

		if($order_count>0)
			$result['name'] = $name.'跑单量（'.$order_count.'单）';
		else
			$result['name'] = $name.'（跑客）';
	}
//		dump('父节点电话：'.$parent_info['mobile'].'（跑客）'.'  /父id '.$parent_id . ' /父类别 '.$parent_type);
	$ret = $app_distribution->where(array('recom_person_id' => $parent_id, 'recom_person_type' => $parent_type))
							->field('recommended_person_id,recommended_person_type')->select();

	if($ret){
		$children = array();
		foreach($ret as $key=>$value){
			$chree = recom_tree($value['recommended_person_id'],$value['recommended_person_type']);
			$result['children'][$key]=$chree;
		}
	}

	return $result;
}

/**
 * 根据ID获取大客户名称
 * @param $uid 用户ID
 * @return mixed
 *
 */
function getShopName($shop_id)
{
	if(!$shop_id)
		return '否';
	$app_users = M("user_shop");
	$ret = $app_users->where(array('shop_id'=>$shop_id))->field('shop_name')->find();
	return $ret['shop_name'];
}

/**
 * 获取跑客的推荐人的名字或电话
 * @param $dispatch_id
 */
function getPnRecommend($dispatch_id){
	$recom_obj = M('recommend')->where(array('recommended_person_id'=>$dispatch_id,'recommended_person_type'=>2))->find();
	if(!$recom_obj)
		return '';
	
	if($recom_obj['recom_person_type']==1){
		$user_obj = M('app_users')->field('mobile')->where('user_id='.$recom_obj['recom_person_id'])->find();
		$recom_name = $user_obj['mobile'];
	}elseif ($recom_obj['recom_person_type']==2){
		$user_obj = M('dispatch')->field('dispatch_name')->where('dispatch_id='.$recom_obj['recom_person_id'])->find();
		$recom_name = $user_obj['dispatch_name'];
	}
	return $recom_name;
}

/**
 * 推荐关系用户的下单量树
 */
//static $result = array();
//function recom_finishorder_tree($parent_id, $parent_type)
//{
//
//	if( !$parent_id || !$parent_type)
//		return "";
//	$app_distribution = M("recommend");
//	$app_user_db = M("app_users");
//	$dispatch_db = M('dispatch');
//	$order_db = M('order');
//
//	if($parent_type == 1 ){
//		$parent_info = $app_user_db->where(array('user_id' => $parent_id))->field('mobile')->find();
//		$order_count = $order_db->where(array('status' => 7 ,'user_id' => $parent_id))->count();
//		if($order_count>0)
//			$result['name'] = $parent_info['mobile'].'下单量（'.$order_count.'单）';
//		else
//			$result['name'] = $parent_info['mobile'].'（用户）';
//	}
//	elseif($parent_type == 2 ){
//		$parent_info = $dispatch_db->where(array('dispatch_id' => $parent_id))->field('mobile,dispatch_name')->find();
//		$order_count = $order_db->where(array('status' => 7 ,'dispatch_id' => $parent_id))->count();
//		$name = $parent_info['mobile'];
//		if($parent_info['dispatch_name'])
//			$name = $parent_info['dispatch_name'].'('.$parent_info['mobile'].')';
//
//		if($order_count>0)
//			$result['name'] = $name.'跑单量（'.$order_count.'单）';
//		else
//			$result['name'] = $name.'（跑客）';
//	}
////		dump('父节点电话：'.$parent_info['mobile'].'（跑客）'.'  /父id '.$parent_id . ' /父类别 '.$parent_type);
//	$ret = $app_distribution->where(array('recom_person_id' => $parent_id, 'recom_person_type' => $parent_type))
//		->field('recommended_person_id,recommended_person_type')->select();
//
//	if($ret){
//		$children = array();
//		foreach($ret as $key=>$value){
//			$chree = recom_tree($value['recommended_person_id'],$value['recommended_person_type']);
//			$result['children'][$key]=$chree;
//		}
//	}
//
//	return $result;
//}

/**
 * 获取团队的关系用户数
 * @param $company_id
 * @param $start_time
 * @param $end_time
 * @return mixed
 */
function get_company_recomm_user_count($company_id,$start_time,$end_time){
	$recommend_db = M('recommend r1');//推荐人表
	if(!$start_time)
		$start_time = date('Y-m',time()).'-1';
	if(!$end_time)
		$end_time = date('Y-m-d',time());
	$where=" d.company_id = ".$company_id;
		$where = $where." and r1.recommended_time >= '".$start_time." 00:00:00'";

		$where = $where." and r1.recommended_time <= '".$end_time." 23:59:59' ";

	$recommend_user = $recommend_db->join(' left join db_recommend r2 on r1.recommended_person_id = r2.recom_person_id and r1.recommended_person_type = r2.recom_person_type')
		->join(' left join db_recommend r3 on r2.recommended_person_id = r3.recom_person_id and r2.recommended_person_type = r3.recom_person_type')
		->join('db_dispatch d on d.dispatch_id = r1.recom_person_id and r1.recom_person_type=2')
		->where($where.' and r1.recom_person_type=2' .
			' and r2.recommended_person_id is not null' .
			' and( CASE when r3.recommended_person_id is null then r2.recommended_person_type=1 end' .
			' or case when r3.recommended_person_id is not null then r3.recommended_person_type=1 end
            or case when r2.recommended_person_id is not null and r3.recommended_person_id is not null and r3.recommended_person_type=2 then r2.recommended_person_type=1 end )')
		->count();

	return $recommend_user;
}

/**
 * 获取团队推荐的一级用户数
 * @param $company_id
 * @param $start_time
 * @param $end_time
 * @return mixed
 */

function get_recomm_one_user_count($company_id,$start_time,$end_time){
	$recommend_db = M('recommend r1');//推荐人表
	if(!$start_time)
		$start_time = date('Y-m',time()).'-1';
	if(!$end_time)
		$end_time = date('Y-m-d',time());
	$where=" d.company_id = ".$company_id;
	$where = $where." and r1.recommended_time >= '".$start_time." 00:00:00'";

	$where = $where." and r1.recommended_time <= '".$end_time." 23:59:59' ";

	$recom_user = $recommend_db->field('d.company_id,count(r1.recommended_person_id) as one_user_count')
		->join('db_dispatch d on d.dispatch_id = r1.recom_person_id and r1.recom_person_type=2')
		->where( $where.' and r1.recom_person_type=2 and r1.recommended_person_type=1 ')
		->group(' d.company_id')->count();//获取uid推荐跑客记录数
//	dump($recommend_db->getLastSql());
	return $recom_user;
}
/**
 * 根据团队id，获取分公司集合
 */
function getCompanyBranch($comany_id){
	$company_branch_db = M('company_branch');
	if($comany_id)
		$where = 'parent_id='.$comany_id;
	else
		$where="";
	$company_objs = $company_branch_db->where($where)->select();

	return $company_objs;
}

/**
 *是否显示退钱链接
 * @param $order_id
 */
function is_show_return_money($order_id){
	$order_pay_db = M('order_pay');
	$pay_obj = $order_pay_db->field('status,return_status,pay_method')->where(array('order_id'=>$order_id))->find();

	if($pay_obj['return_status'] == 1 && $pay_obj['pay_method'] != 3 && $pay_obj['status']==1)
		return true;
	else
		return false;
}

/**
 * 根据id和转单端类别
 * @param $id
 * @param $client
 * @return string
 */
function get_turn_operator($id,$client){

		if($client==1){//手机端
			$app_manager = M('app_manager')->field('user_name')->where(array('id'=>$id))->find();
			return $app_manager['user_name'];
		}elseif ($client==2){//平台
			$users = M('users')->field('user_login')->where(array('id'=>$id))->find();
			return $users['user_login'];
		}
	return '';
}

/**
 * 根据订单id查询订单是否是转单
 * @param $order_id
 * @return string
 */
function is_order_trun($order_id){
	$trun_db = M('order_turn');
	$order_count = $trun_db->where(array('order_id'=>$order_id))->count();
	if($order_count > 0 )
		return '是';
	else
		return '否';
}
/**
 * 获得推荐的跑客
 * @param $recom_id
 * @param $utype
 * @return mixed
 */
function get_recom_pn_count($recom_id,$utype){
	//推荐的跑客数量
	$recommend_db = M('recommend r1');//推荐人表
	$recom_pn_count = $recommend_db->where(array('recom_person_id' => $recom_id, 'recom_person_type' => $utype, 'recommended_person_type' => 2))->count();//获取uid推荐跑客记录数

	return $recom_pn_count;
}
/**
 * 获得推荐的用户数
 * @param $recom_id
 * @param $utype
 * @return mixed
 */
function get_recom_user_count($recom_id,$utype){
	//推荐的跑客数量
	$recommend_db = M('recommend r1');//推荐人表
	$recom_user_count = $recommend_db->where(array('recom_person_id' => $recom_id, 'recom_person_type' => $utype, 'recommended_person_type' => 1))->count();//获取uid推荐用户记录数

	return $recom_user_count;
}

/**
 * 获得关系用户数
 * @param $recom_id
 * @param $utype
 * @return mixed
 */
function get_recom_count($recom_id,$utype){
	//推荐的跑客数量
	$recommend_db = M('recommend r1');//推荐人表

	//一级跑客和用户推荐的用户记录数（包括一级的跑客和用户）
	$recommend_pn_two_three_totalcount = $recommend_db->join(' left join db_recommend r2 on r1.recommended_person_id = r2.recom_person_id and r1.recommended_person_type = r2.recom_person_type')
		->join(' left join db_recommend r3 on r2.recommended_person_id = r3.recom_person_id and r2.recommended_person_type = r3.recom_person_type')
		->where(' r1.recom_person_id=' . $recom_id . ' and r1.recom_person_type=' . $utype .
			' and r2.recommended_person_id is not null' .
			' and( CASE when r3.recommended_person_id is null then r2.recommended_person_type=1 end' .
			' or case when r3.recommended_person_id is not null then r3.recommended_person_type=1 end
                                                         or case when r2.recommended_person_id is not null and r3.recommended_person_id is not null and r3.recommended_person_type=2 then r2.recommended_person_type=1 end )')
		->count();

	return $recommend_pn_two_three_totalcount;
}
/**
 * 逆地址解析location参数传入的参数格式是(纬度lat，经度lng)
 */
function get_route_address($lat,$log){
	$request_address = 'http://api.map.baidu.com/geocoder/v2/?location='.$lat.','.$log.'&output=json&pois=0&ak=oZduCbhCfT0SVjLqjfGB8TPe4edy14MG&from=3&to=6';
	$ch = curl_init($request_address);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	$cexeCute = curl_exec($ch);
	curl_close($ch);

	$address_arr = json_decode($cexeCute,true);

	return $address_arr['result']['formatted_address'];
}

/**
 * 获取跑客未完成订单的个数
 * @param $dispatch_id
 */
function get_no_finish_order($dispatch_id){
	if(!$dispatch_id)
		return 0;
	$order_resmsm_db = M('order_resmsm r');
	$ret_count = $order_resmsm_db
		->where(array('dispatch_id'=>$dispatch_id,'pay_status'=>1,'status'=>array('egt'=>1)))
		->count();//当前此跑客未完成的订单记录数
	return $ret_count;
}

/**
 * 根据id，类别，获得姓名
 * @param $uid
 * @param $utype
 * @return string
 */
function get_user_pk_name($uid,$utype){
	if(!$uid || !$utype)
		return '';
	if($utype==1){
		$user_db = M('app_users a');
		$user_obj = $user_db ->field('mobile,s.shop_name')->where(array('a.user_id'=>$uid))
			->join(' left join db_user_shop s on a.is_shop = s.shop_id')
			->find();
		if($user_obj && $user_obj['shop_name'])
			return $user_obj['shop_name'];
		else
			return $user_obj['mobile'];
	}elseif($utype == 2 ){
		$dispatch_db = M('dispatch');
		$dispatch_obj = $dispatch_db->field('dispatch_name')->where(array('dispatch_id'=>$uid))->find();
		return $dispatch_obj['dispatch_name'];
	}else
		return '';

}
/**
 * 根据id，类别，获得钱包明细
 * @param $uid
 * @param $utype
 * @return string
 */
function get_purse_type($utype,$purse_type){
	if(!$purse_type || !$utype)
		return '';
	if($utype==1){
		$type_arr = array("1"=>'充值',"2"=>'消费',"3"=>'退款',"4"=>'代收货款结算',"5"=>'提款',"6"=>'推荐奖励');
	}elseif($utype == 2 ){
		$type_arr = array("1"=>'跑腿收入',"2"=>'垫付',"3"=>'帮币兑换',"4"=>'提现支出',"5"=>'推荐奖励',"6"=>'保险金额',"7"=>'履约金',"8"=>'违约金',"9"=>'已退金额',"10"=>'奖励',"11"=>'结算');;

	}else
		return '';
	return $type_arr[$purse_type];

}


/**
 * 根据跑客id，提款记录id，获取余额总和
 * @param $dispatch_id 跑客id
 * @param $cash_record_id 提款记录
 * @return float|mixed
 */
function get_dispatch_balance_amount($dispatch_id,$cash_record_id){
	$dispatch_b_db = M('dispatch_balance');
	$sum_amount = $dispatch_b_db->where(array('dispatch_id'=>$dispatch_id,'cash_record_id'=>$cash_record_id))->getField('sum_amount');

	if($sum_amount)
		return $sum_amount;
	else
		return number_format("0",2);
}

/**
 * 根据用户id，充值记录id，获取余额总和
 * @param $user_id 用户id
 * @param $recharge_record_id 充值记录id
 * @return float|mixed
 */
function get_user_balance_amount($user_id,$recharge_record_id){
	$user_b_db = M('user_purse');
	$sum_amount = $user_b_db->where(array('user_id'=>$user_id,'recharge_record_id'=>$recharge_record_id))->getField('sum_amount');

	if($sum_amount)
		return $sum_amount;
	else
		return number_format("0",2);
}